package com.raccoonagents.tools.cascet2d.util;

import java.util.ArrayList;
import java.util.List;

import org.lwjgl.input.Keyboard;

import com.raccoonagents.tools.cascet2d.interfaces.IKeyboardListener;
import com.raccoonagents.tools.cascet2d.model.events.KeyEvent;
/**
 * a class for creating and dispatching keyboard events.
 * @author jabi
 *
 */
public class KeyboardEventFactory {
	private final static List<IKeyboardListener> listeners = new ArrayList<IKeyboardListener>();
	private static int lastKey;
	private static TypeMode typeMode;
	
	private enum TypeMode{
		TYPED,
		PRESSED,
		RELEASED;
	}
	
	public static void addKeyboardListener(final IKeyboardListener listener){
		listeners.add(listener);
	}

	public static void removeKeyboardListener(final IKeyboardListener listener){
		listeners.remove(listener);
	}
	
	
	
	public static void dispatchKeyEvents(){
		Keyboard.poll();
		Keyboard.next();
		final char c = Keyboard.getEventCharacter();
		lastKey = Keyboard.getEventKey();				
		if(c != 0){
			
			if(Keyboard.isKeyDown(lastKey) && typeMode == TypeMode.RELEASED){
				typeMode = TypeMode.TYPED;				
				for(final IKeyboardListener l : listeners){
					l.acceptKeyEvent(new KeyEvent(c, Keyboard.getEventKey(), KeyEvent.EventType.TYPED));
				}				
			} else if(Keyboard.isKeyDown(lastKey) && typeMode == TypeMode.TYPED || typeMode == TypeMode.PRESSED) {
				typeMode = TypeMode.PRESSED;
				for(final IKeyboardListener l : listeners){
					l.acceptKeyEvent(new KeyEvent(c, Keyboard.getEventKey(), KeyEvent.EventType.PRESSED));
				}				
				
			}
		}else{
			typeMode = TypeMode.RELEASED;
		}
					
	}
}
